<template>
  <div class="edit-plant">
    <h2>{{ isEditing ? '编辑植物' : '新增植物' }}</h2>
    <el-form ref="formRef" :model="plant" :rules="rules" label-width="100px">
      <el-form-item label="植物名称" prop="name">
        <el-input v-model="plant.name" placeholder="请输入植物名称" />
      </el-form-item>

      <el-form-item label="分类" prop="category">
        <el-input v-model="plant.category" placeholder="请输入植物分类" />
      </el-form-item>

      <el-form-item label="库存" prop="stock">
        <el-input-number v-model="plant.stock" :min="0" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="savePlant">
          {{ isEditing ? '更新' : '新增' }}
        </el-button>
        <el-button @click="router.back()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { usePlantStore } from '@/stores/plantStore';
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const plantStore = usePlantStore();
const formRef = ref(null);

const plant = ref({
  id: null,
  name: '',
  category: '',
  stock: 0
});

const isEditing = ref(false);

const rules = {
  name: [
    { required: true, message: '请输入植物名称', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请输入植物分类', trigger: 'blur' }
  ],
  stock: [
    { required: true, message: '请输入库存数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '库存数量不能为负数', trigger: 'blur' }
  ]
};

onMounted(() => {
  if (route.params.id) {
    isEditing.value = true;
    const id = Number(route.params.id);
    const found = plantStore.plants.find(p => p.id === id);
    if (found) {
      plant.value = { ...found };
    }
  }
});

const savePlant = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    if (isEditing.value) {
      plantStore.updatePlant(plant.value);
      ElMessage.success('植物信息更新成功');
    } else {
      plant.value.id = Date.now();
      plantStore.addPlant(plant.value);
      ElMessage.success('植物信息新增成功');
    }
    router.push('/plants');
  } catch (error) {
    ElMessage.error('保存失败，请检查表单信息');
  }
};
</script>

<style scoped>
.edit-plant {
  padding: 20px;
  max-width: 600px;
  margin: 0 auto;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
